package com.base.test.mutual.utils;

import com.alibaba.fastjson.JSON;
import com.base.commons.tools.utils.HttpConnectUtil;
import com.base.test.mutual.properties.RfsProperties;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 任森平
 */
@Log4j2
@Configuration
@EnableConfigurationProperties(RfsProperties.class)
public class RFSHttpUtils {
    @Autowired
    private RfsProperties rfsProperties;

    /**
     * 上传文件
     * @param multipartFile 文件对象
     * @param requestId 请求id
     * @return 返回上传成功后的路径地址
     */

    public String uploadFile(MultipartFile multipartFile, String requestId, String filename) {
        Resource resource = multipartFile.getResource();
        return uploadFile(resource,requestId,filename);
    }

    /**
     * 上传文件
     * @param filePath 文件路径
     * @param requestId 请求id
     * @return 返回上传成功后的路径地址
     */
    public String uploadFile(String filePath,String requestId,String filename) {
        FileSystemResource fileSystemResource = new FileSystemResource(filePath);
        return uploadFile(fileSystemResource,requestId,filename);
    }

    private String uploadFile(Resource resource,String requestId,String filename) {
        String filePath = StringUtils.EMPTY;
        if(resource == null) {
            return filePath;
        }
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType(MediaType.MULTIPART_FORM_DATA_VALUE);
        headers.setContentType(type);
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        form.add("file", resource);
        form.add("appKey", rfsProperties.getAppKey());
        form.add("appToken", rfsProperties.getAppToken());
        form.add("fileGroup", rfsProperties.getFileGroup());
        //若filename为空,则获取资源文件的文件名名称
        if(StringUtils.isBlank(filename)) {
            filename = resource.getFilename();
        }
        try {
            String url = rfsProperties.getHost() + rfsProperties.getUploadFileUrl();
            log.info("开始上传文件,file文件-->{},requestId:-->{},url为:-->{}", filename,requestId,url);
            ResponseEntity response = HttpConnectUtil.tempHttp(form, url, headers, "post", new HashMap<>(), Map.class);
            log.info("结束上传文件,file文件-->{},requestId:-->{},请求返回结果为:-->{}", filename,requestId,JSON.toJSONString(response));
            if (isResponseSuccess(response)) {
                Map<String, Object> body = (Map<String, Object>) response.getBody();
                if (isResponseResultSuccess(body)) {
                    List<String> filePaths = (List<String>) body.get("Data");
                    if(CollectionUtils.isEmpty(filePaths)) {
                        return filePath;
                    }
                    return filePaths.get(0);
                }
            }
        }catch (Exception e) {
            log.info("上传文件,file文件-->{},requestId:-->{},上传失败原因:-->{}",filename,requestId,JSON.toJSONString(e.getMessage()));
        }
        return filePath;
    }

    /**
     * 压缩文件
     *
     * @param filePaths 服务器路径
     * @return
     */
    public String compressFile(List<String> filePaths,String fileName,String requestId) {
        String compressFilePath = StringUtils.EMPTY;
        if(CollectionUtils.isEmpty(filePaths)) {
            return compressFilePath;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("appKey", rfsProperties.getAppKey());
        param.put("appToken", rfsProperties.getAppToken());
        param.put("fileList", filePaths);
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE);
        headers.setContentType(type);

        try {
            String url = rfsProperties.getHost() + rfsProperties.getCompressUrl();
            log.info("开始压缩文件,file文件-->{},requestId:-->{},url:-->{}",fileName,requestId,url);
            ResponseEntity post = HttpConnectUtil.tempHttp(param, url, headers, "post", new HashMap<>(), Map.class);
            log.info("结束压缩文件,file文件-->{},requestId:-->{},请求返回结果为:-->{}",fileName,requestId,JSON.toJSONString(post));
            if (isResponseSuccess(post)) {
                Map<String, Object> body = (Map<String, Object>) post.getBody();
                if (isResponseResultSuccess(body)) {
                    return (String) body.get("Data");
                }
            }
        }catch (Exception e) {
            log.info("压缩文件,file文件-->{},requestId:-->{},压缩失败原因:-->{}",fileName,requestId, JSON.toJSONString(e.getMessage()));
        }
        return compressFilePath;
    }

    private boolean isResponseSuccess(ResponseEntity responseEntity) {
        return HttpStatus.OK.value() == responseEntity.getStatusCodeValue();
    }

    private boolean isResponseResultSuccess(Map<String, Object> map) {
        if(map == null || map.isEmpty()) {
            return false;
        }
        int responseResult = (int) map.get("ResponseResult");
        return responseResult == 1;
    }
}
